Ext.define("MyApp.controller.Appointment",{
    extend: "Ext.app.Controller",
	
    config: {
		views: [
			'AddAppointment',
			'appointmentList',
			'EditAppointment'
		],
		models: [
			'Appointments'
		],
		stores: [
			'Appointments',
			'LocalAppointments'
		],
        refs: { 
            appointmentList : "appointmentlist",
            editAppointment : {
                selector: 'editappointment',
                xtype: 'editappointment',
                autoCreate: true
            },
			// addAppointment  : {
                // selector: '#mypanel',
                // xtype: 'mypanel',
                // autoCreate: true
            // },
			saveAppointment  : '#addAppSave'

        },
        control: {
            'appointmentlist': {
                initialize: "appointmentListLoad"
            },
			'appointmentlist button#settings': {
                tap: function() {
					console.log("settings clicked");
					Ext.Viewport.setActiveItem('settingspanel',{type:'slide', direction:'right'});
										App.dispatch({controller:"Setting",action:"SettingsLoad"});
				
					
				}
            },
			'appointmentlist button#create': {
                tap: function() {
					console.log("add app clicked");
					Ext.Viewport.setActiveItem('addappointment',{type:'slide', direction:'right'});
					this.addAppointmentLoad();
				}
            },
			'addappointment button#save' : {
				tap: "onSaveApp"
				
			},			
			
			'addappointment button#saveSendSMS' : {
				tap: "onSendSMS"
			},
			
			'appointmentlist list#applist': {
				editAppointmentCommand: "onEditApp"
			},
			
			'addappointment': {
				initialize: "addAppointmentLoad"
			},
			
			'addappointment datetimepickerfield#starttime': {
				change: function(obj,date) {

					var endtime = Ext.ComponentQuery.query('addappointment datetimepickerfield[itemId="endtime"]').pop();
					var localstore = Ext.getStore("LocalSettings");
					localstore.load();
					var record = localstore.getAt(0);
					
					if  (typeof record != 'undefined'){
						var d = new Date(date);
						console.log(d);
						console.log(d.getMinutes());
						console.log(record.data.applength);
						d.setMinutes(d.getMinutes() + parseInt(record.data.applength));
						console.log(d.getMinutes());
						endtime.setValue(d);
					}
				}
			},
			
			'editappointment button#back': {
				tap: function(){
					Ext.Viewport.setActiveItem('appointmentlist',{type:'slide', direction:'right'});
				}
			},
			
			'editappointment button#save': {
				tap: "onSaveApp"
			},
			
			'editappointment button#delete': {
				tap: "onDeleteApp"
			}
			
        }
    },
	
	addAppointmentLoad: function() {
		console.log("inside add app load");
		var storage = window.localStorage;
		var userID = storage.getItem("UserID");
		
		var form = Ext.ComponentQuery.query('formpanel[itemId="appointmentForm"]').pop();
		form.reset();
		
		var userIdField = Ext.ComponentQuery.query('addappointment hiddenfield[itemId="userId"]').pop();
		userIdField.setValue(userID);
		//Load the default settings
		var localstore = Ext.getStore("LocalSettings");
		localstore.load();
		var record = localstore.getAt(0);
		
		if  (typeof record != 'undefined'){
		
			if (record.data.sendcalendar == "true"){
				var cal = Ext.ComponentQuery.query('checkboxfield[itemId="calendar"]').pop();
				cal.check();
			}
			
			if (record.data.sendmap == "true"){
				var map = Ext.ComponentQuery.query('checkboxfield[itemId="maplink"]').pop();
				map.check();
			}
				
			var location = Ext.ComponentQuery.query('textfield[itemId="mapaddress]').pop();
			location.setValue(record.data.mapaddress);
		}
	},
	
	appointmentListLoad: function(){
	
		var storage = window.localStorage;	
		var userID = storage.getItem("UserID");
		var list = Ext.ComponentQuery.query('appointmentlist list[itemId="applist"]').pop();
		var localstore = list.getStore();
		
		localstore.load();
		console.log(localstore.getCount());
		if ((localstore.getCount())== 0) {
			console.log("inside webrequest for data");
			
			
			var store = Ext.getStore("Appointments");
			var proxy = store.getProxy();
			proxy.setExtraParam("id", userID);
			
			store.getProxy().setExtraParam("id", userID);
			store.load({
				callback: function(records, operation, success) {
					Ext.each(records,function(record){
						record.dirty = true;
					});
					localstore.add(records);
					localstore.sync();	
				}
			});	
			
			console.log(localstore.getCount());	
			
		
		
		}
		else {
			localstore.each(function(item){
			
			});
		}
		var timezone = storage.getItem("timezone");
		localstore.filter();
	},
    onEditApp: function(record) {
		console.log(record.data.mapaddress);
		this.getEditAppointment().down("#editAppointmentForm").setRecord(record);
		this.getEditAppointment().down("#editAppointmentForm").down("#email").setValue(record.data.email);
		this.getEditAppointment().down("#editAppointmentForm").down("#starttime").setValue(record.data.starttime);
		this.getEditAppointment().down("#editAppointmentForm").down("#endtime").setValue(record.data.endtime);
		this.getEditAppointment().down("#editAppointmentForm").down("#date").setValue(record.data.date);
		this.getEditAppointment().down("#editAppointmentForm").down("#mapaddress").setValue(record.data.mapaddress);
		this.getEditAppointment().down("#editAppointmentForm").down("#appointmentid").setValue(record.data.appointmentid);
		Ext.Viewport.setActiveItem('editappointment', { type: "slide", direction: "left" });
		this.getEditAppointment().down("#editAppointmentForm").down("#appointmentid").focus();
		

        
    },
	
	onSaveApp: function(){
		console.log("inside save app");
		var activeItem = Ext.getClassName(Ext.Viewport.getActiveItem());
		if (activeItem == 'MyApp.view.EditAppointment'){
			 form = Ext.ComponentQuery.query('editappointment formpanel[itemId="editAppointmentForm"]').pop();
			 values = form.getValues();
		}
		else {
			form = Ext.ComponentQuery.query('addappointment formpanel[itemId="appointmentForm"]').pop();
			values = form.getValues();
		}
		var time = new Date(values.starttime);
		values.starttime = time.toISOString();
		
		var time2 = new Date(values.endtime);
		values.endtime = time2.toISOString();
		
		var date = new Date(values.date);
		values.date = date.toISOString();
		
		var validation = this.validateEntry(values,"");
		
		if (validation == 0) {
			return;
		}
		console.log("appointment id" + values.appointmentid);
		Ext.Ajax.request({
			url: 'http://appt.elasticbeanstalk.com/appointment.php',
			params: values,
			
			success: function(response){
				var text = response.responseText;
				var result = Ext.decode(text);
				var data = Ext.JSON.decode(response.responseText.trim());

				
				
				if (data.Success == 'true'){
					//refresh local store
					 var localstore = Ext.getStore("LocalAppointments");
						
					values.starttime = data.startTime;
					values.endtime = data.endTime;
					values.maplink = data.maplink;
					values.calendar = data.calendar;
					values.reminder = data.reminder;
					values.date = data.date;
					values.appointmentid = data.id;
					values.mapaddress = data.mapaddress;

					var newRecord = new MyApp.model.Appointments(values);
					console.log(data.method);
					if (data.method == 'insert'){
						localstore.add(newRecord);
						localstore.sync();
					}
					else {
						var oldrec = localstore.findRecord("appointmentid",data.id);
						console.log(oldrec.date);
						localstore.remove(oldrec);
						localstore.sync();
						localstore.add(newRecord);
						localstore.sync();
					}
					
					var localsettings = Ext.getStore("LocalSettings");
					if (localsettings.getCount() > 0) {
						var record = localsettings.getAt(0);
						
						if (record.data.calendar == 'true') {
							//create native calendar app
							var title = "Appointment With " + values.firstname;
							var location = values.map;
							var description = values.notes;
							
							var date = new Date(values.date);
								var day = date.getUTCDate();
								var month = date.getUTCMonth();
								var year = date.getUTCFullYear();
								var offset = date.getTimezoneOffset();
							
							var time = new Date(values.starttime);
								time.setUTCDate(day);
								time.setUTCMonth(month);
								time.setUTCFullYear(year);
							var time2 = new Date(values.endtime);
								time2.setUTCDate(day);
								time2.setUTCMonth(month);
								time2.setUTCFullYear(year);

							var startDateTime = Ext.Date.format(time,"Y-m-d H:i:s"); // ISO 8601 date
							var endDateTime = Ext.Date.format(time2,"Y-m-d H:i:s");
							var cal = new CalendarPlugin;
							cal.createEvent(title, location, description, startDateTime, endDateTime);
						}
					}
					Ext.Viewport.setActiveItem('appointmentlist',{type:'slide', direction:'right'});
				}
			},
			
			failure: function(response){
				
				Ext.Msg.alert('error', 'error submitting appointment');
				console.log(response.responseText);
			}	
		});
	},
	
	onSendSMS: function() {
		var activeItem = Ext.getClassName(Ext.Viewport.getActiveItem());
		if (activeItem == 'MyApp.view.EditAppointment'){
			 form = Ext.ComponentQuery.query('editappointment formpanel[itemId="editAppointmentForm"]').pop();
			 values = form.getValues();
		}
		else {
			var sentBy = Ext.ComponentQuery.query('addappointment hiddenfield[itemId="sentby"]').pop();
			sentBy.setValue('SMS');
			form = Ext.ComponentQuery.query('addappointment formpanel[itemId="appointmentForm"]').pop();
			values = form.getValues();
			
		}
		var time = new Date(values.starttime);
		values.starttime = time.toISOString();
		
		var time2 = new Date(values.endtime);
		values.endtime = time2.toISOString();
		
		var date = new Date(values.date);
		values.date = date.toISOString();
		
		var validation = this.validateEntry(values,"SMS");
		
		if (validation == 0) {
			return;
		}
		

		Ext.Ajax.request({
			url: 'http://appt.elasticbeanstalk.com/appointment.php',
			params: values,
			
			success: function(response){
				var text = response.responseText;
				var result = Ext.decode(text);

				var data = Ext.JSON.decode(response.responseText.trim());
				var urltosend = "http://appt.cc/" + data.shortURL;
				var mapurl = "http://addr.cc/" + data.shortURL;

				if (data.Success == 'true'){

					message = "Appointment confirmation with ";
					
					var localsettings = Ext.getStore("LocalSettings");
					if (localsettings.getCount() > 0) {
						
						var record = localsettings.getAt(0);
						message += record.data.name;
					}
					console.log(data.date);
					console.log(Ext.Date.format(new Date(data.date),"Y-m-d"));
					message += " on " + Ext.Date.format(new Date(data.date),"m/d/Y");
					message += " @ " + Ext.Date.format(new Date(data.startTime),"g:iA");
					
					if (values.calendar != null) {
						var shorturl;
						message += " Add to Calendar " + urltosend;
					}
					 
					if (values.maplink != null){
						
						if (values.mapaddress != null && values.mapaddress != ''){
						message += " Map " + mapurl;
						}
					}
					console.log(message);
					window.plugins.SmsPlugin.send(values.mobile, 
						message, 
						function () { 
						   alert('Message sent successfully');	
						},
						function (e) {
							alert('Message Failed:' + e);
						}
					);
					
					var localstore = Ext.getStore("LocalAppointments");
					values.starttime = data.startTime;
					values.endtime = data.endTime;
					values.maplink = data.maplink;
					values.calendar = data.calendar;
					values.reminder = data.reminder;
					values.date = data.date;
					values.appointmentid = data.id;
					values.mapaddress = data.mapaddress;
					
					var newRecord = new MyApp.model.Appointments(values);
					if (data.method == 'insert'){
						localstore.add(newRecord);
						localstore.sync();
					}
					else {
						var oldrec = localstore.findRecord("appointmentid",data.id);
						console.log(oldrec.date);
						localstore.remove(oldrec);
						localstore.sync();
						localstore.add(newRecord);
						localstore.sync();
					}
					
					
					if (localsettings.getCount() > 0) {
						var record = localsettings.getAt(0);
						
						if (record.data.calendar == 'true') {
							//create native calendar app
							var title = "Appointment With " + values.firstname;
							var location = values.map;
							var description = values.notes;
							
							var date = new Date(values.date);
								var day = date.getUTCDate();
								var month = date.getUTCMonth();
								var year = date.getUTCFullYear();
								var offset = date.getTimezoneOffset();
							
							var time = new Date(values.starttime);
								time.setUTCDate(day);
								time.setUTCMonth(month);
								time.setUTCFullYear(year);
							var time2 = new Date(values.endtime);
								time2.setUTCDate(day);
								time2.setUTCMonth(month);
								time2.setUTCFullYear(year);

							var startDateTime = Ext.Date.format(time,"Y-m-d H:i:s"); // ISO 8601 date
							var endDateTime = Ext.Date.format(time2,"Y-m-d H:i:s");
							var cal = new CalendarPlugin;
							cal.createEvent(title, location, description, startDateTime, endDateTime);
						}
					}
					Ext.Viewport.setActiveItem('appointmentlist', {type:'slide', direction:'left'});
				}
			},
			
			failure: function(response){
				Ext.Msg.alert('error', 'error submitting appointment');
				console.log(response.responseText);
			}		
		});
		
		
	},
	
	onDeleteApp: function() {
		form = Ext.ComponentQuery.query('editappointment formpanel[itemId="editAppointmentForm"]').pop();
		values = form.getValues();
		console.log("inside delete");
		console.log(values.appointmentid);
		
		Ext.Ajax.request({
			url: 'http://appt.elasticbeanstalk.com/deleteappointment.php',
			params: values,
			
			success: function(response){
				console.log("inside success function");
				var text = response.responseText;
				var data = Ext.JSON.decode(response.responseText.trim());
				if (data.Success == 'true'){
					console.log("inside data.Success");
					console.log(values.appointmentid);
					var localstore = Ext.getStore("LocalAppointments");
					var oldrec = localstore.findRecord("appointmentid",values.appointmentid);
					
					if  (typeof oldrec != 'undefined'){
						localstore.remove(oldrec);
						localstore.sync();
						Ext.Viewport.setActiveItem('appointmentlist', {type:'slide', direction:'left'});
					}
				}
			},
			failure: function(response){
			
			}
		});
		
	},
	
	validateEntry: function(values,calledfrom) {
		console.log("inside validation");
		var result = 1;
		if (!values.firstname && !values.lastname) {
			alert("Firstname/lastname required");
			result = 0;
		}
		
		if (!values.date) {
			alert("Appointment date required");
			result = 0;
		}
		
		if (!values.starttime && !values.endtime) {
			alert("Start/End time required");
			result = 0;
		}
		
		switch (calledfrom) {
		
			case "SMS":
				if (!values.mobile) {
					alert("Mobile number required");
					result = 0;
				}
			break;
			case "email":
				if (!values.email) {
					alert("Email address required");
					result = 0;
				}
			break;	
			
		}
		
		return result;
	}
});